// Utility functions for local storage

// Types
export type HabitRecord = {
  id: string;
  name: string;
  icon: string;
  streak: number;
  completed: boolean;
  dateCreated: string;
  lastCompleted?: string;
};

export type MetricData = {
  waterIntake: {
    current: number;
    goal: number;
    history: { date: string; value: number }[];
  };
  steps: {
    current: number;
    goal: number;
    history: { date: string; value: number }[];
  };
  sleep: {
    current: number;
    goal: number;
    history: { date: string; value: number }[];
  };
  habits: {
    completed: number;
    total: number;
  };
};

// Storage keys
const HABITS_STORAGE_KEY = 'health_tracker_habits';
const METRICS_STORAGE_KEY = 'health_tracker_metrics';

// Default data
const defaultHabits: HabitRecord[] = [
  { id: '1', name: '饮水', icon: '💧', streak: 5, completed: false, dateCreated: new Date().toISOString() },
  { id: '2', name: '运动', icon: '🏃', streak: 3, completed: false, dateCreated: new Date().toISOString() },
  { id: '3', name: '阅读', icon: '📚', streak: 7, completed: false, dateCreated: new Date().toISOString() },
  { id: '4', name: '冥想', icon: '🧘', streak: 2, completed: false, dateCreated: new Date().toISOString() },
];

const defaultMetrics: MetricData = {
  waterIntake: { 
    current: 2.2, 
    goal: 2.5,
    history: Array.from({ length: 7 }, (_, i) => ({
      date: new Date(Date.now() - (6-i) * 24 * 60 * 60 * 1000).toISOString(),
      value: Math.random() * 2 + 1.5 // Random value between 1.5 and 3.5
    }))
  },
  steps: { 
    current: 9408, 
    goal: 10000,
    history: Array.from({ length: 7 }, (_, i) => ({
      date: new Date(Date.now() - (6-i) * 24 * 60 * 60 * 1000).toISOString(),
      value: Math.floor(Math.random() * 4000 + 7000) // Random value between 7000 and 11000
    }))
  },
  sleep: { 
    current: 6.4, 
    goal: 8,
    history: Array.from({ length: 7 }, (_, i) => ({
      date: new Date(Date.now() - (6-i) * 24 * 60 * 60 * 1000).toISOString(),
      value: Math.random() * 3 + 5 // Random value between 5 and 8
    }))
  },
  habits: { completed: 3, total: 4 },
};

// Get data from local storage
export const getHabits = (): HabitRecord[] => {
  try {
    const storedHabits = localStorage.getItem(HABITS_STORAGE_KEY);
    return storedHabits ? JSON.parse(storedHabits) : defaultHabits;
  } catch (error) {
    console.error('Error retrieving habits from local storage:', error);
    return defaultHabits;
  }
};

export const getMetrics = (): MetricData => {
  try {
    const storedMetrics = localStorage.getItem(METRICS_STORAGE_KEY);
    return storedMetrics ? JSON.parse(storedMetrics) : defaultMetrics;
  } catch (error) {
    console.error('Error retrieving metrics from local storage:', error);
    return defaultMetrics;
  }
};

// Save data to local storage
export const saveHabits = (habits: HabitRecord[]): void => {
  try {
    localStorage.setItem(HABITS_STORAGE_KEY, JSON.stringify(habits));
  } catch (error) {
    console.error('Error saving habits to local storage:', error);
  }
};

export const saveMetrics = (metrics: MetricData): void => {
  try {
    localStorage.setItem(METRICS_STORAGE_KEY, JSON.stringify(metrics));
  } catch (error) {
    console.error('Error saving metrics to local storage:', error);
  }
};

// Add a new habit
export const addHabit = (habit: Omit<HabitRecord, 'id' | 'dateCreated'>): HabitRecord[] => {
  const habits = getHabits();
  const newHabit: HabitRecord = {
    ...habit,
    id: Date.now().toString(),
    dateCreated: new Date().toISOString(),
  };
  
  const updatedHabits = [...habits, newHabit];
  saveHabits(updatedHabits);
  
  return updatedHabits;
};

// Delete a habit
export const deleteHabit = (habitId: string): HabitRecord[] => {
  const habits = getHabits();
  const updatedHabits = habits.filter(habit => habit.id !== habitId);
  saveHabits(updatedHabits);
  
  return updatedHabits;
};

// Update a habit
export const updateHabit = (habitId: string, updates: Partial<HabitRecord>): HabitRecord[] => {
  const habits = getHabits();
  const updatedHabits = habits.map(habit => 
    habit.id === habitId ? { ...habit, ...updates } : habit
  );
  saveHabits(updatedHabits);
  
  return updatedHabits;
};

// Record a habit completion
export const recordHabit = (habitId: string): { habits: HabitRecord[], metrics: MetricData } => {
  const habits = getHabits();
  const metrics = getMetrics();
  
  const updatedHabits = habits.map(habit => 
    habit.id === habitId ? { 
      ...habit, 
      completed: true, 
      streak: habit.streak + 1,
      lastCompleted: new Date().toISOString()
    } : habit
  );
  
  const completedCount = updatedHabits.filter(h => h.completed).length;
  const updatedMetrics = {
    ...metrics,
    habits: {
      ...metrics.habits,
      completed: completedCount,
    }
  };
  
  saveHabits(updatedHabits);
  saveMetrics(updatedMetrics);
  
  return { habits: updatedHabits, metrics: updatedMetrics };
};

// Reset daily habits
export const resetDailyHabits = (): HabitRecord[] => {
  const habits = getHabits();
  
  const updatedHabits = habits.map(habit => ({
    ...habit,
    completed: false,
  }));
  
  saveHabits(updatedHabits);
  return updatedHabits;
};

// Update water intake
export const updateWaterIntake = (amount: number): MetricData => {
  const metrics = getMetrics();
  const today = new Date().toISOString().split('T')[0];
  
  const updatedMetrics = {
    ...metrics,
    waterIntake: {
      ...metrics.waterIntake,
      current: Math.min(metrics.waterIntake.current + amount, metrics.waterIntake.goal),
      history: [
        ...metrics.waterIntake.history.filter(item => !item.date.startsWith(today)),
        { date: new Date().toISOString(), value: Math.min(metrics.waterIntake.current + amount, metrics.waterIntake.goal) }
      ]
    }
  };
  
  saveMetrics(updatedMetrics);
  return updatedMetrics;
};

// Update steps
export const updateSteps = (steps: number): MetricData => {
  const metrics = getMetrics();
  const today = new Date().toISOString().split('T')[0];
  
  const updatedMetrics = {
    ...metrics,
    steps: {
      ...metrics.steps,
      current: metrics.steps.current + steps,
      history: [
        ...metrics.steps.history.filter(item => !item.date.startsWith(today)),
        { date: new Date().toISOString(), value: metrics.steps.current + steps }
      ]
    }
  };
  
  saveMetrics(updatedMetrics);
  return updatedMetrics;
};

// Update sleep
export const updateSleep = (hours: number): MetricData => {
  const metrics = getMetrics();
  const today = new Date().toISOString().split('T')[0];
  
  const updatedMetrics = {
    ...metrics,
    sleep: {
      ...metrics.sleep,
      current: hours,
      history: [
        ...metrics.sleep.history.filter(item => !item.date.startsWith(today)),
        { date: new Date().toISOString(), value: hours }
      ]
    }
  };
  
  saveMetrics(updatedMetrics);
  return updatedMetrics;
}; 